#!/bin/bash

: '

# 安装时不打补丁，仅用于测试
touch /exbin/wbox_do_not_patch_when_install


wbox安装脚本整理记录，基于开源的 mobox 安装脚本(package-manager.sh)
====================================================================
0). proot 挂载 termux-rootfs
    command+=" -b $LINUX_DIR/opt/apps/termux:/data/data/com.termux/files"

1). package-manager(非必须，wbox脚本参数自这个shell文件)
    # wine32/64分体
    PRIVATE_TOKEN=glpat-Xs4HfrCkMpbedkPycqzP
    PROJECT_ID=52465323

    # wine32/64一体											<<==	建议使用一体wine
    PRIVATE_TOKEN=glpat-h5r7HjKoPKZPxmfg79xs
    PROJECT_ID=54240888
    PKGNAME="package-manager"
    FILE_SAVETO="package-manager.sh"
    wget --retry-connrefused --tries=0 --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/repository/files/$PKGNAME/raw?ref=main" -O $FILE_SAVETO

2). 其它包的下载
    SW_ITEM=box64-binaries
    PKGNAME="${SW_ITEM}.tar.xz"
    FILE_SAVETO="${SW_ITEM}.tar.xz"
    wget --retry-connrefused --tries=0 --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/repository/files/$PKGNAME/raw?ref=main" -O $FILE_SAVETO


	到目前为止可选的wine版本(2024.05.27)
	wine-9.0-staging-wow64 \
	wine-8.18-staging-wow64 \
	wine-8.18-vanilla-wow64 \
	wine-9.1-vanilla-wow64 \
	wine-9.2-vanilla-wow64 \
	wine-9.3-vanilla-wow64 \
#



# wine虚拟桌面的图标保存在：(https://askubuntu.com/questions/433623/how-to-add-shortcut-onto-wine-desktop)
"~/.wine/drive_c/users/Public/Desktop/"


# wine开始菜单路径:
"~/.wine/drive_c/ProgramData/Microsoft/Windows/Start Menu"


# 运行
/opt/apps/termux/usr/glibc/bin/box64 /opt/apps/termux/usr/glibc/wine-9.3-vanilla-wow64/bin/wine explorer /desktop=arbname,1920x1200 "C:\...\...\application.exe"
/opt/apps/termux/usr/glibc/bin/box64 /opt/apps/termux/usr/glibc/wine-9.3-vanilla-wow64/bin/wine explorer
/opt/apps/termux/usr/glibc/bin/box64 /opt/apps/termux/usr/glibc/wine-9.3-vanilla-wow64/bin/wine explorer
/opt/apps/termux/usr/glibc/bin/box64 /opt/apps/termux/usr/glibc/wine-9.3-vanilla-wow64/bin/wine start /unix %f
C:\windows>start /unix /usr/bin/jwm		# cmd 命令行下启动 linux 端的程序

# virgl 加速
/opt/apps/termux/usr/glibc/opt/virgl/libvirgl_test_server.so  --help
/opt/apps/termux/usr/glibc/opt/virgl/libvirgl_test_server.so  --socket-path="${LINUX_DIR}/tmp/.virgl_test" --use-egl-surfaceless --use-gles 2>&1

export GALLIUM_DRIVER=virpipe
export MESA_GL_VERSION_OVERRIDE=4.0


# 其它不要紧的
export PREFIX=/data/data/com.termux/files/usr
export LD_PRELOAD=/data/data/com.termux/files/usr/lib/libtermux-exec.so
unset LD_PRELOAD
unset PREFIX


汉化 => 实测无效！
https://github.com/lsl330/Box64Droid-For-Chinese/releases/download/Chinese-LANG-Pack/Chinese-LANG-Pack.tar.xz

安装脚本：
https://raw.githubusercontent.com/lsl330/Box64Droid-For-Chinese/main/mobox/install

echo "zh_CN.utf8" > /exbin/z/usr/glibc/opt/locale.conf

cp -f /sdcard/download/Chinese-LANG-Pack/SimSun.ttc         $PREFIX/glibc/share/fonts/SimSun.ttc
cp -f /sdcard/download/Chinese-LANG-Pack/PMingLiU-TW.ttf    $PREFIX/glibc/share/fonts/PMingLiU-TW.ttf
cp -f /sdcard/download/Chinese-LANG-Pack/locale-archive-cn  $PREFIX/glibc/lib/locale/locale-archive
echo -e " 替换mobox为中文环境"
sed -i 's/C.utf8/zh_CN.utf8/g' $PREFIX/glibc/opt/locale.conf
echo -e " 替换TFM为中文版"
cp -f /sdcard/download/Chinese-LANG-Pack/TFM.exe $PREFIX/glibc/opt/apps/tfm.exe




'

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

SWNAME=wbox
SWVER=1.8.19

# 注意安装顺序，后装者依赖前装者
DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
app_dir=/exbin/z
WBOXDIR=${app_dir}
WBOXUSR=${app_dir}/usr

if [ 1 -eq 0 ]; then
	WINE_HOME_P=${ZZ_USER_HOME}/.wine
	WINE_HOME_O=${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${WINE_HOME_P}
else
	WINE_HOME_P=${app_dir}/.wine
	WINE_HOME_O=${APP_INTERNAL_DIR}/z/.wine
fi


. ./ezapp/wbox/patch.rc


WBOX_WINE=wine-9.3-vanilla-wow64

declare -a WBOX_PKGS=(\
	box64-binaries \
	dxvk \
	glibc-prefix \
	prefix-apps \
	scripts \
	turnip \
	virgl-mesa \
	wined3d \
	libudev \
	en-ru-locale \
	${WBOX_WINE} \
)

function wboxDownload() {
  filesaveto=$1
  url=$2
  echo "正在下载：${filesaveto} <= ${url}"
  tmp_wdir=`pwd`
  echo "工作目录：${tmp_wdir}"
  echo "保存路径：${filesaveto}"
  if [ -f ${filesaveto}.downloading ]; then echo "上次未完整下载，正在删除临时文件后重新下载"; rm -rf ${filesaveto}; else touch ${filesaveto}.downloading ;fi
	#[ -f ${filesaveto} ] || wget -q --retry-connrefused --tries=0 --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "${url}" -O ${filesaveto}
	 [ -f ${filesaveto} ] || wget -q --retry-connrefused --tries=0 "${url}" -O ${filesaveto}
  rlt_code=$?
  if [ $rlt_code -ne 0 ]; then
    rm -rf "${filesaveto}" 2>/dev/null
  fi
  rm -rf ${filesaveto}.downloading

  return ${rlt_code}
}

function sw_download() {
	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh gitlab.com`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	# mobox packages
	case "${CURRENT_VM_ARCH}" in
		"arm64")
			# # gitlab项目ID：wine32/64分体
			# PRIVATE_TOKEN=glpat-Xs4HfrCkMpbedkPycqzP
			# PROJECT_ID=52465323

			# # gitlab项目ID：wine32/64一体											<<==	建议使用一体wine
			PRIVATE_TOKEN=glpat-h5r7HjKoPKZPxmfg79xs
			PROJECT_ID=54240888

			for SW_ITEM in "${WBOX_PKGS[@]}"; do
				PKGNAME="${SW_ITEM}.tar.xz"
				FILE_SAVETO="./downloads/${SW_ITEM}.tar.xz"
				wboxDownload "${FILE_SAVETO}" "https://gitlab.com/api/v4/projects/$PROJECT_ID/repository/files/$PKGNAME/raw?ref=main"
				exit_if_fail $? "下载失败，软件包：${SW_ITEM}"
			done
		;;
		*) exit_unsupport ;;
	esac

	echo "正在下载茶壶演示程序"
	demoapp=./downloads/demoapp.zip
	swUrl=${APP_URL_DLSERVER}/EnvMapping_DX9.zip
	download_file2 "${demoapp}" "${swUrl}"
	exit_if_fail $? "下载失败，网址：${swUrl}"

}

function sw_install() {
	rm -rf /exbin/apps
	rm -rf ${WBOXDIR}/.wine
	rm -rf ${WINE_HOME_P}

	# command -v tmx >/dev/null 2>&1 || ./scripts/tmx.sh
	[ -d ${WBOXDIR} ]  || ./scripts/tmx.sh
	exit_if_fail $? "tmx 安装失败"

	command -v patchelf >/dev/null 2>&1 || sudo apt-get install -y patchelf
	exit_if_fail $? "patchelf 安装失败"

	command -v readelf >/dev/null 2>&1 || sudo apt-get install -y binutils
	exit_if_fail $? "readelf 安装失败"

	command -v file >/dev/null 2>&1 || sudo apt-get install -y file
	exit_if_fail $? "file 安装失败"

	command -v unzip >/dev/null 2>&1 || sudo apt-get install -y unzip
	exit_if_fail $? "unzip 安装失败"
	
	for SW_ITEM in "${WBOX_PKGS[@]}"; do
		PKGNAME="${SW_ITEM}.tar.xz"
		FILE_SAVETO="./downloads/${SW_ITEM}.tar.xz"
		echo "正在解压 ${SW_ITEM} . . ."
		tar -xJf ${FILE_SAVETO} --overwrite -C ${WBOXUSR}
		exit_if_fail $? "解压失败，软件包：${DEB_PATH}"
	done

	echo "正在解压 可运行于wine中的3D茶壶测试程序"
	mkdir -p  ${WBOXDIR}/3D茶壶 2>/dev/null
	unzip -oq ${demoapp} -d ${WBOXDIR}/3D茶壶
	exit_if_fail $? "解压失败，软件包：${demoapp}"


	echo "正在创建相关文件 . . ."
	create_files

	if [ ! -f /exbin/wbox_do_not_patch_when_install ]; then
		echo "正在打elf补丁 . . ."
		doPatch
	fi
}

function sw_create_desktop_file() {

	echo "正在生成rc文件"
	cat <<- EOF > ${WBOXDIR}/config.rc
		export WBOX_WINE="${WBOX_WINE}"

		# export HOME=${APP_INTERNAL_DIR}/vm/${CURRENT_OS_NAME}${ZZ_USER_HOME}

		export   WBOXDIR=${APP_INTERNAL_DIR}/z
		export   WBOXUSR=\${WBOXDIR}/usr
		export    PREFIX=\${WBOXDIR}/usr
		export GLIBC_BIN=\${WBOXDIR}/usr/glibc/bin
		export WINE_PATH=\${WBOXDIR}/usr/glibc/${WBOX_WINE}

		. \${WBOXDIR}/usr/glibc/opt/scripts/configs
		load_configs

		# wine 主目录
		export WINEPREFIX=${WINE_HOME_O}
		export   LOG_PATH=\${VM_ROOT}/tmp/wbox

		# wine 语言
        export LANG=zh_CN.UTF-8
        export LANGUAGE=zh_CN.UTF-8
        export LC_CTYPE=zh_CN.UTF-8
        export LC_NUMERIC=zh_CN.UTF-8
        export LC_TIME=zh_CN.UTF-8
        export LC_COLLATE=zh_CN.UTF-8
        export LC_MONETARY=zh_CN.UTF-8
        export LC_MESSAGES=zh_CN.UTF-8
        export LC_PAPER=zh_CN.UTF-8
        export LC_NAME=zh_CN.UTF-8
        export LC_ADDRESS=zh_CN.UTF-8
        export LC_TELEPHONE=zh_CN.UTF-8
        export LC_MEASUREMENT=zh_CN.UTF-8
        export LC_IDENTIFICATION=zh_CN.UTF-8
        export LC_ALL=zh_CN.UTF-8	  


		if [ "\${RESOLUTION}" == "" ]; then
		export RESOLUTION=1024x768
		fi
		# export STARTUP_COMPATIBILITY_MODE=0

		export PATH=\$PATH:\${WBOXUSR}/glibc/bin:\${WBOXUSR}/bin
		unset  BOX64_LD_LIBRARY_PATH
		export BOX64_LD_LIBRARY_PATH=\${WBOXUSR}/glibc/lib:\${WBOXUSR}/glibc/lib/x86_64-linux-gnu
		export BOX64_NOBANNER=1
		export BOX64_LOG=5

		unset BOX64_DYNAREC_BIGBLOCK
		unset WINEESYNC
		unset WINEESYNC_TERMUX
		unset BOX64_DYNAREC_CALLRET

		export TERMUX_PREFIX=\${PREFIX}
		export TMPDIR=\${VM_ROOT}/tmp
		export TERM=vt100

	    # cd \${WINE_PATH}/bin

	EOF

	echo "正在生成启动脚本"
	tmpfile=/usr/bin/${SWNAME}
	cat <<- EOF > ${tmpfile}
		#!/bin/bash
		# echo "\$@"
		# echo "\$*"

		narg=\$#
		exepath="\$1"
		# echo "\$exepath"

		# until [ \$# -eq 0 ]
		# do
		# echo "第一个参数为: \$1 参数个数为: \$#"
		# shift
		# done


		if [ "\$FIRSTTIME_RUN_CHECK" == "" ]; then
			# if [ ! -d ~/.wine ]; then
			# if [ ! -d ${WBOXDIR}/.wine ]; then
			if [ ! -d ${WINE_HOME_P} ]; then
				sleep 1
				export FIRSTTIME_RUN_CHECK=no
				cmd -e 'bash -c "wbox init || read -s -n1 -p \"按任意键退出\""'
			fi
		fi

		if [ -f ${WBOXDIR}/glchanged ]; then
			echo "显卡驱动已变更，正在重新打elf补丁..."

			( cd /exbin/tools/zzswmgr && /exbin/tools/zzswmgr/scripts/wbox.sh quick_patch )

			rm -rf ${WBOXDIR}/glchanged
		fi

		# set -x	# echo on
		if [[ \$exepath == "/"* ]]; then
			exedir=\$(realpath "\$exepath")
			exedir=\$(dirname "\$exedir")
			cd "\$exedir"
		fi
		# set +x	# echo off

		# gxmessage -title "提示" "\$exepath"
		# gxmessage -title "提示" "\$1"
		# gxmessage -title "提示" \`pwd\`
		# echo "pwd: "\`pwd\`

		# if [[ \$DISPLAY == ":"* ]]; then
		# 	echo "export DISPLAY=127.0.0.1\${DISPLAY}"										> ${WBOXDIR}/rt_vars.rc
		# else
		# 	echo "export DISPLAY=\${DISPLAY}"												> ${WBOXDIR}/rt_vars.rc
		# fi
		echo "export DISPLAY=\${DISPLAY}"													> ${WBOXDIR}/rt_vars.rc
		echo "export PULSE_SERVER=\${PULSE_SERVER}"											>>${WBOXDIR}/rt_vars.rc
		echo "export VM_ROOT=\${APP_INTERNAL_DIR}/vm/\${CURRENT_OS_NAME}"					>>${WBOXDIR}/rt_vars.rc
		echo "export    HOME=\${APP_INTERNAL_DIR}/vm/\${CURRENT_OS_NAME}/home/"\`whoami\`	>>${WBOXDIR}/rt_vars.rc

		# echo ": exepath:  \$exepath"
		# set -x	# echo on
		if [ \$narg -eq 1 ]; then
			if [[ "\$exepath" == *".lnk" ]]; then
				[ -d ${WBOXDIR}/lnkCache ] || mkdir -p ${WBOXDIR}/lnkCache
				cp -f "\${exepath}"  ${WBOXDIR}/lnkCache/
				cd ${WBOXDIR}/lnkCache
				exepath=\`basename "\${exepath}"\`

				# echo "正在把路径中的空格全部替换成 '|'"
				# exepath=\${exepath// /|}
				exec /exbin/droidexec ${APP_INTERNAL_DIR}/tools/zzswmgr/ezapp/wbox/wbox.sh "\$exepath"
			else
				# echo "正在把路径中的空格全部替换成 '|'"
				# exepath=\${exepath// /|}
				exec /exbin/droidexec ${APP_INTERNAL_DIR}/tools/zzswmgr/ezapp/wbox/wbox.sh "\$exepath"
			fi
		else
			exec /exbin/droidexec ${APP_INTERNAL_DIR}/tools/zzswmgr/ezapp/wbox/wbox.sh \$@
		fi
		# set +x	# echo off
	EOF
	chmod 755 ${tmpfile}

	echo "正在生成桌面文件"
	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=${SWNAME}
		GenericName=${SWNAME}
		Exec=${SWNAME} explorer
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}-reset.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=wb重置
		GenericName=wb重置
		Exec=${WBOXDIR}/gldriver/wbox-reset.sh
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}-virdsk.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=wb桌面
		GenericName=wb桌面
		Exec=${SWNAME} explorer /desktop=shell
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}-term.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=wb终端
		GenericName=wb终端
		Exec=${SWNAME} start cmd
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}-conf.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=wb配置
		GenericName=wb配置
		Exec=${SWNAME} winecfg
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}-tools.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=wb调参
		GenericName=wb调参
		Exec=/exbin/tools/zzswmgr/ezapp/wbox/wbtools.py
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
	EOF
	cp2desktop ${tmpfile}
	chmod a+x /exbin/tools/zzswmgr/ezapp/wbox/wbtools.py

	tmpfile=${DIR_DESKTOP_FILES}/winexe.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=运行exe软件
		GenericName=运行exe软件
		Exec=${SWNAME} %f
		Terminal=false
		Type=Application
		Icon=/exbin/tools/zzswmgr/ezapp/wbox/wbox.png
		Categories=System
		MimeType=application/x-dosexec;application/x-ms-dos-executable;application/x-ms-shortcut;application/x-msi;application/vnd.microsoft.portable-executable
	EOF


	# prompt_for_reboot "提示" "安装已完成，请重启一次"  &
	gxmessage -title "提示" "安装已完成，双击桌面上红色的 wbox 图标即可启动" -center  &

	# # 初始化wine，在这里初始化不成功
	# sudo -u ${ZZ_USER_NAME} wbox init

	# #启动茶壶测试程序
	# sudo -u ${ZZ_USER_NAME} wbox &

}


if [ "${action}" == "quick_patch" ]; then
	QUICK_PATCH=1
	doPatch
	exit 0
fi

if [ "${action}" == "patch" ]; then
	doPatch
	exit 0
fi

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1

	rm -rf /exbin/apps
	rm -rf ${WINE_HOME_P}
	rm -rf ${WBOXDIR}/usr/glibc
	rm -rf /usr/bin/${SWNAME}
	rm2desktop ${SWNAME}.desktop
	rm2desktop ${SWNAME}-virdsk.desktop
	rm2desktop ${SWNAME}-term.desktop
	rm2desktop ${SWNAME}-conf.desktop
	rm2desktop ${SWNAME}-reset.desktop
	rm2desktop ${SWNAME}-tools.desktop
	rm2desktop 显卡驱动
	sed -i "/盘/d"  ${ZZ_USER_HOME}/.config/gtk-3.0/bookmarks
	apt-get clean
else

	sw_download
	sw_install
	sw_create_desktop_file
fi

